package com.chis.activemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.concurrent.atomic.AtomicInteger;

public class TestProducer {

    
        //ActiveMq 的默认用户名
        private static final String USERNAME = "admin";
        //ActiveMq 的默认登录密码
        private static final String PASSWORD = "admin";
        //ActiveMQ 的链接地址
        private static final String BROKEN_URL = "tcp://10.88.88.107:61616";


        //链接工厂
//        ConnectionFactory connectionFactory;
        //链接对象
//        Connection connection;
        //事务管理
        private Session session;


        public void init(){
            try {
                //创建一个链接工厂
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
                //从工厂中创建一个链接
                Connection connection  = connectionFactory.createConnection();
                //开启链接
                connection.start();
                //创建一个事务（这里通过参数可以设置事务的级别）
//                session = connection.createSession(true,Session.SESSION_TRANSACTED);
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

        public void sendMessage(String disname,String msgcontent){
            try {
                //创建一个消息队列
                Queue queue = session.createQueue(disname);
                //消息生产者
//                MessageProducer messageProducer = null;

                MessageProducer messageProducer = session.createProducer(queue);

                    //创建一条消息
                    TextMessage msg = session.createTextMessage(msgcontent);

                    //发送消息
                    messageProducer.send(msg);
                    //提交事务
//                    session.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    public static void main(String[] args) {
        TestProducer testProducer = new TestProducer();
        testProducer.init();
        testProducer.sendMessage("wlj","imwf");
//        try {
//            testProducer.connection.close();
//        } catch (JMSException e) {
//            e.printStackTrace();
//        }
        System.out.println("success");
    }

}
